import { Component, OnInit, OnDestroy }      from '@angular/core';
import { Router, ActivatedRoute }            from '@angular/router';
import { FormGroup, FormBuilder, Validators} from '@angular/forms';
import { Store }                             from '@ngrx/store';
import { environment }                       from '../../../environments/environment';
import { AuthService }                       from '../../core/services/auth.service';
import { AppState }                          from '../../interfaces';
import { getAuthStatus }                     from '../../auth/reducers/selectors';
import { Subscription }                      from 'rxjs/Subscription';
import { ToasterService }                    from '../../share/toastr/toastr.service';


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.css'],
  providers: [ToasterService]
})
// export class LoginComponent implements OnInit, OnDestroy {
export class LoginComponent implements OnInit {

  signInForm: FormGroup;
  title =     environment.AppName;
  loginSubs: Subscription;
  returnUrl: string;
  formSubmit = false;

  constructor(private fb:            FormBuilder,
              private authService:   AuthService,
              private route:         ActivatedRoute,
              private router:        Router,
              private store:         Store<AppState>,
              public  toasrtService: ToasterService
  ) {
    // this.redirectIfUserLoggedIn();
  }

  ngOnInit() {
    this.initForm();
    // this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
    console.log('login url: ', this.returnUrl);
  }

  onSubmit() {
    const values    = this.signInForm.value;
    const keys      = Object.keys(values);
    this.formSubmit = true;

    console.log('sign in form data --- ', values);

    if ( this.signInForm.valid) {
      console.log('validator form data ---', values);
      this.loginSubs = this.authService.login(values).subscribe(data => {
        // const error  = data.error;
        // if (error) {
        //   keys.forEach(val => {
        //     this.pushErrorFor(val, error);
        //   });
        // }
        this.router.navigate(['/home']);
        this.toasrtService.successful('login successfuly !');
      }
      ,
      errors => {
        this.toasrtService.errors('login errors !');
      }
      );
    }else {
      keys.forEach(val => {
        const ctrl = this.signInForm.controls[val];
        if (!ctrl.valid) {
          this.pushErrorFor(val, null);
          ctrl.markAsTouched();
        }
      });
      this.toasrtService.errors('login faield ! ');
    }
  }

  private pushErrorFor(ctrl_name: string, msg: string) {
    this.signInForm.controls[ctrl_name].setErrors({'msg': msg});
  }

  initForm () {
    // const email = '';
    const username = '';
    const password = '';

    this.signInForm = this.fb.group({
      'password': [password, Validators.required],
      'username': [username, Validators.required]
    });
  }

  redirectIfUserLoggedIn () {
    this.store.select(getAuthStatus).subscribe(
      data => {
        // if (data === true) { console.log('dada...', data); this.router.navigate([this.returnUrl]);
        console.log('redirect if user loing function ...');
        console.log('data-->', data);

         if (data === true) { 
           this.router.navigate(['/home']);
           console.log('navigate url : ----');
        }
      }
    );
  }

  // ngOnDestroy () {
  //   if (this.loginSubs) {
  //     this.loginSubs.unsubscribe();
  //     console.log('unsubscribe --->', this.loginSubs.unsubscribe());
  //   }
  // }

}
